<template>
  <div class="report-center">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">📊 报表中心</span>
          <div class="header-actions">
            <el-input 
              v-model="searchKeyword" 
              placeholder="搜索报表" 
              clearable 
              style="width: 300px;"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="goToDesigner">
              <el-icon><Plus /></el-icon>
              新建报表
            </el-button>
          </div>
        </div>
      </template>

      <!-- 分类标签 -->
      <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange">
        <el-tab-pane label="全部报表" name="all" />
        <el-tab-pane label="销售报表" name="sales" />
        <el-tab-pane label="财务报表" name="finance" />
        <el-tab-pane label="库存报表" name="inventory" />
        <el-tab-pane label="采购报表" name="purchase" />
        <el-tab-pane label="自定义" name="custom" />
      </el-tabs>

      <!-- 视图切换 -->
      <div class="view-switch">
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button value="card">
            <el-icon><Grid /></el-icon>
            卡片
          </el-radio-button>
          <el-radio-button value="list">
            <el-icon><Document /></el-icon>
            列表
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 卡片视图 -->
      <div v-if="viewMode === 'card'" class="card-view">
        <el-row :gutter="20">
          <el-col 
            :xs="24" 
            :sm="12" 
            :md="8" 
            :lg="6" 
            v-for="report in filteredReports" 
            :key="report.id"
          >
            <el-card class="report-card" shadow="hover">
              <div class="report-preview">
                <img :src="report.thumbnail" v-if="report.thumbnail" alt="报表预览" />
                <div v-else class="preview-placeholder">
                  <el-icon :size="48"><DataLine /></el-icon>
                </div>
              </div>
              <div class="report-info">
                <h3 class="report-title">{{ report.name }}</h3>
                <p class="report-desc">{{ report.description }}</p>
                <div class="report-meta">
                  <el-tag size="small">{{ getCategoryName(report.category) }}</el-tag>
                  <span class="meta-item">
                    <el-icon><User /></el-icon>
                    {{ report.creator }}
                  </span>
                  <span class="meta-item">
                    <el-icon><View /></el-icon>
                    {{ report.views }}
                  </span>
                </div>
              </div>
              <div class="report-actions">
                <el-button type="primary" size="small" @click="handleViewReport(report)">
                  查看
                </el-button>
                <el-button size="small" @click="handleEdit(report)">
                  编辑
                </el-button>
                <el-dropdown trigger="click">
                  <el-button size="small" circle>
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleCopy(report)">
                        <el-icon><DocumentCopy /></el-icon>
                        复制
                      </el-dropdown-item>
                      <el-dropdown-item @click="handleShare(report)">
                        <el-icon><Share /></el-icon>
                        分享
                      </el-dropdown-item>
                      <el-dropdown-item @click="handleExport(report)">
                        <el-icon><Download /></el-icon>
                        导出
                      </el-dropdown-item>
                      <el-dropdown-item divided @click="handleDelete(report)">
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 空状态 -->
        <el-empty v-if="filteredReports.length === 0" description="暂无报表数据" />
      </div>

      <!-- 列表视图 -->
      <div v-else class="list-view">
        <el-table :data="filteredReports" border stripe>
          <el-table-column prop="name" label="报表名称" width="250" />
          <el-table-column prop="category" label="分类" width="120">
            <template #default="{ row }">
              <el-tag size="small">{{ getCategoryName(row.category) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" show-overflow-tooltip />
          <el-table-column prop="creator" label="创建人" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="160" />
          <el-table-column prop="views" label="查看次数" width="100" />
          <el-table-column label="操作" width="300" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleViewReport(row)">查看</el-button>
              <el-button link type="success" @click="handleEdit(row)">编辑</el-button>
              <el-button link type="warning" @click="handleExport(row)">导出</el-button>
              <el-button link type="info" @click="handleShare(row)">分享</el-button>
              <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="filteredReports.length"
        :page-sizes="[12, 24, 48, 96]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 报表查看对话框 -->
    <el-dialog 
      v-model="viewDialogVisible" 
      :title="currentReport?.name"
      width="90%"
      :fullscreen="true"
    >
      <div class="report-view">
        <div class="report-toolbar">
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button @click="handlePrint">
            <el-icon><Printer /></el-icon>
            打印
          </el-button>
          <el-button @click="handleDownload">
            <el-icon><Download /></el-icon>
            下载
          </el-button>
        </div>
        <div class="report-content">
          <div class="report-display">
            <h2>{{ currentReport?.name }}</h2>
            <p class="report-meta-info">
              <span>创建人: {{ currentReport?.creator }}</span>
              <span>创建时间: {{ currentReport?.createTime }}</span>
              <span>分类: {{ getCategoryName(currentReport?.category) }}</span>
            </p>
            <el-divider />
            
            <!-- 模拟报表内容 -->
            <div class="demo-content">
              <el-alert 
                title="报表内容预览" 
                type="info" 
                :closable="false"
                style="margin-bottom: 20px;"
              >
                <p>{{ currentReport?.description }}</p>
              </el-alert>

              <!-- 示例数据图表 -->
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <span>销售趋势</span>
                    </template>
                    <div class="chart-demo">
                      <el-icon :size="64" color="#409eff"><TrendCharts /></el-icon>
                      <p>折线图展示区域</p>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <span>数据统计</span>
                    </template>
                    <div class="chart-demo">
                      <el-icon :size="64" color="#67c23a"><PieChart /></el-icon>
                      <p>饼图展示区域</p>
                    </div>
                  </el-card>
                </el-col>
              </el-row>

              <!-- 示例数据表格 -->
              <el-card style="margin-top: 20px;">
                <template #header>
                  <span>详细数据</span>
                </template>
                <el-table :data="demoTableData" border>
                  <el-table-column prop="date" label="日期" width="120" />
                  <el-table-column prop="product" label="产品" width="200" />
                  <el-table-column prop="sales" label="销量" width="100" />
                  <el-table-column prop="amount" label="金额" width="120">
                    <template #default="{ row }">
                      ¥{{ row.amount.toLocaleString() }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="trend" label="趋势" />
                </el-table>
              </el-card>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 分享对话框 -->
    <el-dialog v-model="shareDialogVisible" title="分享报表" width="500px">
      <el-form label-width="100px">
        <el-form-item label="分享链接">
          <el-input 
            :value="shareLink" 
            readonly
          >
            <template #append>
              <el-button @click="handleCopyLink">复制</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期">
          <el-select v-model="shareExpiry">
            <el-option label="1天" value="1" />
            <el-option label="7天" value="7" />
            <el-option label="30天" value="30" />
            <el-option label="永久" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="访问密码">
          <el-switch v-model="sharePassword" />
          <el-input 
            v-if="sharePassword" 
            v-model="sharePasswordValue" 
            placeholder="请输入密码"
            style="margin-top: 10px;"
          />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, Plus, Grid, Document, DataLine, User, View, MoreFilled,
  Edit, DocumentCopy, Share, Delete, Refresh, Printer, Download,
  TrendCharts, PieChart
} from '@element-plus/icons-vue'

const router = useRouter()

const searchKeyword = ref('')
const activeCategory = ref('all')
const viewMode = ref('card')
const viewDialogVisible = ref(false)
const shareDialogVisible = ref(false)
const currentReport = ref(null)
const shareLink = ref('https://report.example.com/share/abc123')
const shareExpiry = ref('7')
const sharePassword = ref(false)
const sharePasswordValue = ref('')

// 示例表格数据
const demoTableData = ref([
  { date: '2024-01-01', product: 'iPhone 15', sales: 145, amount: 869550, trend: '上升' },
  { date: '2024-01-02', product: 'MacBook Pro', sales: 89, amount: 1780000, trend: '上升' },
  { date: '2024-01-03', product: 'iPad Air', sales: 234, amount: 1170000, trend: '稳定' }
])

// 报表列表
const reportList = ref([
  {
    id: 1,
    name: '月度销售报表',
    description: '展示月度销售数据分析和趋势',
    category: 'sales',
    creator: '张三',
    createTime: '2024-01-15 10:30',
    views: 156,
    thumbnail: ''
  },
  {
    id: 2,
    name: '库存统计报表',
    description: '实时库存数据统计和预警分析',
    category: 'inventory',
    creator: '李四',
    createTime: '2024-01-14 14:20',
    views: 89,
    thumbnail: ''
  },
  {
    id: 3,
    name: '财务收支明细',
    description: '详细的财务收入和支出报表',
    category: 'finance',
    creator: '王五',
    createTime: '2024-01-13 09:15',
    views: 234,
    thumbnail: ''
  },
  {
    id: 4,
    name: '采购订单汇总',
    description: '采购订单的汇总统计和分析',
    category: 'purchase',
    creator: '赵六',
    createTime: '2024-01-12 16:45',
    views: 67,
    thumbnail: ''
  },
  {
    id: 5,
    name: '客户销售排行',
    description: '客户销售额排行和贡献度分析',
    category: 'sales',
    creator: '张三',
    createTime: '2024-01-11 11:00',
    views: 178,
    thumbnail: ''
  },
  {
    id: 6,
    name: '产品利润分析',
    description: '产品利润率和毛利分析报表',
    category: 'finance',
    creator: '李四',
    createTime: '2024-01-10 15:20',
    views: 92,
    thumbnail: ''
  },
  {
    id: 7,
    name: '库存周转率',
    description: '库存周转率和周转天数分析',
    category: 'inventory',
    creator: '王五',
    createTime: '2024-01-09 09:45',
    views: 123,
    thumbnail: ''
  },
  {
    id: 8,
    name: '采购成本分析',
    description: '采购成本趋势和优化建议',
    category: 'purchase',
    creator: '赵六',
    createTime: '2024-01-08 14:10',
    views: 78,
    thumbnail: ''
  }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 12,
  total: 8
})

// 过滤报表
const filteredReports = computed(() => {
  let result = reportList.value
  
  // 按分类过滤
  if (activeCategory.value !== 'all') {
    result = result.filter(r => r.category === activeCategory.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(r => 
      r.name.toLowerCase().includes(keyword) || 
      r.description.toLowerCase().includes(keyword)
    )
  }
  
  return result
})

// 获取分类名称
const getCategoryName = (category) => {
  const map = {
    sales: '销售',
    finance: '财务',
    inventory: '库存',
    purchase: '采购',
    custom: '自定义'
  }
  return map[category] || category
}

// 分类切换
const handleCategoryChange = () => {
  pagination.page = 1
}

// 搜索
const handleSearch = () => {
  console.log('搜索报表')
}

// 跳转到设计器
const goToDesigner = () => {
  router.push('/report/designer')
}

// 查看报表
const handleViewReport = (report) => {
  currentReport.value = report
  viewDialogVisible.value = true
  // 增加查看次数
  report.views++
}

// 编辑报表
const handleEdit = (report) => {
  router.push({ path: '/report/designer', query: { id: report.id } })
}

// 复制报表
const handleCopy = (report) => {
  const newReport = {
    ...report,
    id: Date.now(),
    name: report.name + ' (副本)',
    createTime: new Date().toLocaleString(),
    views: 0
  }
  reportList.value.push(newReport)
  ElMessage.success(`已复制报表: ${report.name}`)
}

// 分享报表
const handleShare = (report) => {
  currentReport.value = report
  shareLink.value = `https://report.example.com/share/${report.id}`
  shareDialogVisible.value = true
}

// 复制分享链接
const handleCopyLink = () => {
  navigator.clipboard.writeText(shareLink.value).then(() => {
    ElMessage.success('分享链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 删除报表
const handleDelete = (report) => {
  ElMessageBox.confirm(`确定要删除报表 "${report.name}" 吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    const index = reportList.value.findIndex(r => r.id === report.id)
    if (index > -1) {
      reportList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 导出报表
const handleExport = (report) => {
  ElMessageBox.confirm('请选择导出格式', '导出报表', {
    confirmButtonText: 'PDF',
    cancelButtonText: 'Excel',
    distinguishCancelAndClose: true,
    type: 'info'
  }).then(() => {
    ElMessage.success(`正在导出 ${report.name} 为PDF格式`)
  }).catch((action) => {
    if (action === 'cancel') {
      ElMessage.success(`正在导出 ${report.name} 为Excel格式`)
    }
  })
}

// 刷新报表
const handleRefresh = () => {
  ElMessage.success('报表数据已刷新')
}

// 打印报表
const handlePrint = () => {
  ElMessage.info('准备打印...')
  setTimeout(() => {
    window.print()
  }, 500)
}

// 下载报表
const handleDownload = () => {
  ElMessage.success('报表下载中...')
}
</script>

<style scoped>
.report-center {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.view-switch {
  margin: 20px 0;
  display: flex;
  justify-content: flex-end;
}

.card-view {
  margin-top: 20px;
}

.report-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  cursor: pointer;
}

.report-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.report-preview {
  height: 150px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin: -20px -20px 15px;
  border-radius: 4px 4px 0 0;
  color: white;
}

.report-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-placeholder {
  color: white;
  opacity: 0.8;
}

.report-info {
  margin-bottom: 15px;
}

.report-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.report-desc {
  margin: 0 0 12px 0;
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.report-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.report-actions {
  display: flex;
  gap: 8px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.list-view {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.report-view {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.report-toolbar {
  padding: 15px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  gap: 10px;
}

.report-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
  background: white;
}

.report-display {
  max-width: 1200px;
  margin: 0 auto;
}

.report-display h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

.report-meta-info {
  text-align: center;
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
}

.report-meta-info span {
  margin: 0 15px;
}

.demo-content {
  margin-top: 30px;
}

.chart-demo {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  border-radius: 4px;
  color: #909399;
}

.chart-demo p {
  margin-top: 10px;
}

/* 响应式 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    flex-direction: column;
  }
  
  .header-actions .el-input {
    width: 100% !important;
  }
}
</style>
